<template>
  <div>
    <div class="search-container">
      <el-input
        v-model="pestName"
        placeholder="名称"
        style="width: 10%; margin-right: 20px; margin-left: 20px; "
        class="rounded-input"
      />
      <el-select
        v-model="pestType"
        placeholder="类型"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      >
        <el-option label="植物病" value="0"></el-option>
        <el-option label="害虫" value="1"></el-option>
      </el-select>
      <el-select
        v-model="identify"
        placeholder="识别方式"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      >
        <el-option label="AI大模型" value="1"></el-option>
        <el-option label="本地知识库" value="0"></el-option>
      </el-select>
      <el-select
        v-model="createdBy"
        placeholder="创建人"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
        filterable
      >
        <el-option
          v-for="creator in creators"
          :key="creator.id"
          :label="creator.name"
          :value="creator.id"
        />
      </el-select>
      <el-button
        type="text"
        icon="el-icon-search"
        @click="fetchData"
        style="margin-left: 0;"
      ></el-button>
      <el-button
        type="text"
        icon="el-icon-refresh"
        @click="resetSearch"
        style="margin-left: 10px;"
      ></el-button>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAddProtectiveMeasure"
        style="margin-left: 430px;"
      >
        添加病虫害
      </el-button>
    </div>
    <el-table :data="paginatedData" style="width: 100%">
      <el-table-column prop="rowId" label="ID" width="100"></el-table-column>
      <el-table-column prop="pestImage" label="图片" width="155">
        <template slot-scope="scope">
          <img :src="scope.row.pestImage" alt="图片" class="record-image" />
        </template>
      </el-table-column>
      <el-table-column prop="pestName" label="名称" width="140"></el-table-column>
      <el-table-column prop="pestType" label="种类" width="140"></el-table-column>
      <el-table-column prop="identify" label="识别方式" width="140"></el-table-column>
      <el-table-column prop="protective" label="防治措施" width="160"></el-table-column>
      <el-table-column prop="pestFeature" label="特征" width="160"></el-table-column>
      <el-table-column prop="pestIntroduce" label="介绍" width="170"></el-table-column>
      <el-table-column prop="createdBy" label="创建人" width="135"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleUpdate(scope.$index, scope.row)">更新</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      title="添加病虫害"
      :visible.sync="dialogVisibleAdd"
      width="50%"
      @close="cancel"
    >
      <el-form :model="addForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图片">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :http-request="addUpload"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="addForm.pestImage" :src="addForm.pestImage" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称">
              <el-input v-model="addForm.pestName" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="类型">
              <el-select v-model="addForm.pestType" placeholder="请选择类型" style="width: 200px;">
                <el-option label="植物病" value="0"></el-option>
                <el-option label="害虫" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="识别方式">
              <el-select v-model="addForm.identify" placeholder="请选择识别方式" style="width: 200px;">
                <el-option label="AI大模型" value="1"></el-option>
                <el-option label="本地知识库" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="防治措施">
          <el-select v-model="addForm.protective" placeholder="请选择防治措施" multiple>
            <el-option
              v-for="measure in protectiveMeasures"
              :key="measure.id"
              :label="measure.protectiveName"
              :value="measure.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="特点">
          <el-input
            type="textarea"
            v-model="addForm.pestFeature"
            :rows="4"
            placeholder="请输入特点"
            style="width: 500px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="简介" >
          <el-input
            type="textarea"
            v-model="addForm.pestIntroduce"
            :rows="4"
            placeholder="请输入简介"
            style="width: 500px;"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改病虫害"
      :visible.sync="dialogVisibleUpdate"
      width="50%"
    >
      <el-form :model="updateForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图片">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :http-request="updateUpload"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="updateForm.pestImage" :src="updateForm.pestImage" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称">
              <el-input v-model="updateForm.pestName" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="类型">
              <el-select v-model="updateForm.pestType" placeholder="请选择类型" style="width: 200px;">
                <el-option label="植物病" value="0"></el-option>
                <el-option label="害虫" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="识别方式">
              <el-select v-model="updateForm.identify" placeholder="请选择识别方式" style="width: 200px;">
                <el-option label="AI大模型" value="1"></el-option>
                <el-option label="本地知识库" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="防治措施">
          <el-select v-model="updateForm.protective" placeholder="请选择防治措施" multiple>
            <el-option
              v-for="measure in protectiveMeasures"
              :key="measure.id"
              :label="measure.protectiveName"
              :value="measure.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="特点">
          <el-input
            type="textarea"
            v-model="updateForm.pestFeature"
            :rows="4"
            placeholder="请输入特点"
            style="width: 500px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="简介" >
          <el-input
            type="textarea"
            v-model="updateForm.pestIntroduce"
            :rows="4"
            placeholder="请输入简介"
            style="width: 500px;"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleUpdate= false">取 消</el-button>
        <el-button type="primary" @click="updateSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { selectPage, getCreators, getProtective, getById, add, update, deleteById, upload } from '@/api/pest';

export default {
  name: 'Pest',
  data() {
    return {
      tableData: [], // 假设这是从API获取的数据
      currentPage: 1,
      pageSize: 2,
      total: 0,
      pestName: null,
      pestType: null,
      identify: null,
      createdBy: null,
      creators: [],
      dialogVisibleAdd: false,
      dialogVisibleUpdate: false,
      addForm: {
        pestImage: '',
        pestName: '',
        pestType: '',
        identify: '',
        protective: [],
        pestFeature: '',
        pestIntroduce: ''
      },
      protectiveMeasures: [],
      updateForm: {
        id: null,
        pestImage: null,
        pestName: null,
        pestType: null,
        identify: null,
        protective: [],
        pestFeature: null,
        pestIntroduce: null,
      },
    };
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end).map((row,index) => ({
        ...row,
        rowId: start + index + 1
      }))
    },
  },
  created() {
    this.fetchData();
    this.fetchProtectiveMeasures();
  },
  methods: {
    fetchData() {
      const params ={
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        pestName: this.pestName,
        pestType: this.pestType,
        identify: this.identify,
        createdBy: this.createdBy
      };

      // 这是一个获取数据的API调用
      selectPage(params)
        .then(response => {
          this.tableData = response.data.result;
          this.total = response.data.total;
        })
        .catch(error => {
          console.error('获取数据失败', error);
        });

        getCreators()
        .then(response => {
          this.creators = response.data;
        })
        .catch(error => {
          console.error('获取数据失败', error);
        });
    },

    fetchProtectiveMeasures() {
      getProtective()
        .then(response => {
          this.protectiveMeasures = response.data;
        })
        .catch(error => {
          console.error('获取防治措施失败', error);
        });
    },

    handleAddProtectiveMeasure(){
      console.log('新增病虫害！');
      this.dialogVisibleAdd = true;
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    handleUpdate(index, row) {
      // 实现更新逻辑
      console.log('更新', index, row);
      // 你可以在这里调用更新API
      getById(row.id)
        .then(response => {
        this.updateForm = response.data; // 将返回的数据存储到dialogData
        this.dialogVisibleUpdate = true; // 显示对话框
        })
        .catch(error => {
          console.error('更新失败', error);
          this.$message({
              message: response.message,
              type: 'error'
          });
        });
    },
    handleDelete(index, row) {
      // 实现删除逻辑
      console.log('删除', index, row);
      this.$confirm('此操作将永久删除该措施, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实现删除逻辑
        console.log('删除', index, row);
        deleteById(row.id).then(response => {
          console.log(response)
          console.log('删除成功', response);
          if(response.code === 200){
            this.$message({
              message: "删除成功!",
              type: 'success'
            });
          }else{
            this.$message({
              message: response.message,
              type: 'error'
            });
          }
          this.fetchData(); // 重新获取数据
        }).catch(error => {
          console.error('删除失败', error);
        });
      }).catch(() => {
         // 用户点击取消
        this.$message({
          message: '已取消删除~',
          type: 'info'
        });
      })
    }, 

    resetSearch() {
      // 清空搜索框中的所有输入并恢复默认选项
      this.pestName = null,
      this.pestType = null;
      this.identify = null,
      this.createdBy = null,
      this.fetchData(); // 重新获取数据
    },

    resetForm() {
      this.addForm = {
        pestImage: '',
        pestName: '',
        pestType: '',
        identify: '',
        protective: '',
        pestFeature: '',
        pestIntroduce: ''
      };
    },
    cancel(){
      this.dialogVisibleAdd = false;
      this.resetForm();
    },
    handleAvatarSuccess(res, file) {
      this.form.pestImage = URL.createObjectURL(file.raw);
    },

    addUpload(options) {
      const { file } = options;
      const bucket = 'pest-control';             // 固定 bucket
      const objectName = 'image';                // 固定目录名

      upload(file, bucket, objectName)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.addForm.pestImage = response.data; // 接收返回的 URL
            this.$message.success('上传成功');
          } else {
            this.$message.error('上传失败：' + (response.message || '未知错误'));
          }
        })
        .catch(() => {
          this.$message.error('请求出错，请重试');
        });
    },

    updateUpload(options) {
      const { file } = options;
      const bucket = 'pest-control';             // 固定 bucket
      const objectName = 'image';                // 固定目录名

      upload(file, bucket, objectName)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.updateForm.pestImage = response.data; // 接收返回的 URL
            this.$message.success('上传成功');
          } else {
            this.$message.error('上传失败：' + (response.message || '未知错误'));
          }
        })
        .catch(() => {
          this.$message.error('请求出错，请重试');
        });
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    addSubmit() {
      if (
        !this.addForm.pestName ||
        this.addForm.pestType === null ||
        this.addForm.protective === null ||
        this.addForm.identify === null
      ) {
        this.$message({
          message: '内容不能为空',
          type: 'warning'
        });
        return;
      }
      // 提交表单逻辑
      console.log('添加病虫害', this.addForm);
      // 你可以在这里调用API提交数据
      add(this.addForm)
        .then(response => {
          console.log('添加成功', response);
          this.dialogVisible = false;
          if(response.code === 200){
            this.$message({
              message: "添加成功!",
              type: 'success'
            });
            this.dialogVisibleAdd = false;
            this.resetForm();
          }else{
            this.$message({
              message: response.message,
              type: 'error'
            });
          }
          this.fetchData(); // 重新获取数据
        })
        .catch(error => {
          console.error('新增失败', error);
        });
    },
    updateSubmit() {
      // 提交表单逻辑
      console.log('更新病虫害', this.updateForm);
      const updateParams = {
        id: this.updateForm.id,
        pestName: this.updateForm.pestName,
        pestType: this.updateForm.pestType,
        pestImage: this.updateForm.pestImage,
        identify: this.updateForm.identify,
        pestFeature: this.updateForm.pestFeature,
        pestIntroduce: this.updateForm.pestIntroduce,
        protective: this.updateForm.protective
      };

      // 你可以在这里调用API提交数据
      update(updateParams).then(response => {
        console.log('更新成功', response);
        if(response.code == 200){
          this.$message({
            message: '更新成功！',
            type: 'success'
          });
        }else{
          this.$message({
            message: response.data,
            type: 'error'
          });
        }
        this.dialogVisibleUpdate = false; // 关闭对话框
        this.fetchData(); // 重新获取数据
      }).catch(error => {
        console.error('更新失败', error);
      });
    }
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 2px solid #d9d9d9; /* 添加外边框 */
  border-radius: 6px; /* 可选：添加圆角 */
}

.search-container {
  margin-bottom: 20px;
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.rounded-input .el-input__inner {
  border-radius: 20px;
  width: 15%;
  margin-right: 10px;
}


.rounded-input:last-child .el-input__inner {
  border-radius: 20px;
  margin-right: 10px;
}

.el-select .el-input__inner {
  border-radius: 20px;
  width: 15%;
  margin-right: 10px;
}

.el-button--text {
  padding: 0; /* 去掉按钮的内边距 */
  margin-left: 10px; /* 调整按钮的左边距 */
  font-size: 20px;
}

.monitor-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh; /* 确保容器至少占满整个视口高度 */
  padding: 20px;
  box-sizing: border-box;
}

.monitor-table {
  width: 100%;
  flex: 1; /* 使表格内容占据剩余空间 */
  margin-bottom: 20px;
}

.record-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.pagination-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff; /* 确保背景颜色与页面一致 */
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  padding: 10px;
  box-sizing: border-box;
}

.el-table {
  margin-bottom: 60px; /* 根据分页组件的高度调整这个值 */
}
</style>